<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Requests\Dashboard\CareerSkillStoreRequest;
use App\Http\Requests\Dashboard\CareerSkillUpdateRequest;
use App\Http\Requests\Dashboard\NextSkillRequest;
use App\Http\Resources\Dashboard\CareerSkillsResource;
use App\Http\Resources\Dashboard\SkillCareersCollection;
use App\Http\Resources\Dashboard\SkillCareersResource;
use App\Models\Career;
use App\Models\CareerSkill;
use App\Models\Skill;

use App\Http\Controllers\Controller;

use Illuminate\Support\Arr;

class CareerSkillController extends Controller
{
    public function detail(Career $career, Skill $skill)
    {
        return $career->skills()->where('skill_id', $skill->id)->withPivot('complete_percentage')->first();
    }

    public function skills(Career $career)
    {
        return CareerSkillsResource::collection($career->skills);
    }

    public function careers(Skill $skill)
    {
        return SkillCareersResource::collection($skill->careers);
    }

    public function relation(Career $career, Skill $skill)
    {
        $relation = $career->skills()->find($skill->id);
        $next = $relation->pivot->next_skill_id;
        $query = $career->skills()
            ->where(function ($query) use ($next, $skill) {
                $query->whereJsonContains('next_skill_id', $skill->id)//当前节点的先前节点
                ->orWhereIn('skill_id', Arr::wrap($next));//当前节点的后继节点
            })
            ->where('skill_id', '!=', $skill->id)//不包含本节点
            ->get();
        return CareerSkillsResource::collection($query);
    }

    public function attach(CareerSkillStoreRequest $request, Career $career, Skill $skill)
    {
        $career->skills()->attach($skill->id, $request->validated());
    }

    public function update(CareerSkillUpdateRequest $request, Career $career, Skill $skill)
    {
        $career->skills()->updateExistingPivot($skill->id, $request->only(CareerSkill::OTHER_COLUMNS));
    }

    public function addNextSkill(NextSkillRequest $request, Career $career, Skill $skill)
    {
        $careerSkill = CareerSkill::whereSkillId($skill->id)->whereCareerId($career->id)->first();
        $next = array_values(array_unique(array_merge($careerSkill->next_skill_id??[], [intval($request->next_skill_id)])));

        $career->skills()->updateExistingPivot($skill->id, ['next_skill_id' => $next]);

    }

    public function deleteNextSkill(NextSkillRequest $request, Career $career, Skill $skill)
    {
        $careerSkill = CareerSkill::whereSkillId($skill->id)->whereCareerId($career->id)->first();

        $next = array_values(array_filter($careerSkill->next_skill_id, function ($item) use ($request) {
            return $item != $request->next_skill_id;
        }));
        $career->skills()->updateExistingPivot($skill->id, ['next_skill_id' => $next]);

    }

    public function detach(Career $career, Skill $skill)
    {
        $career->skills()->detach($skill->id);
    }
}
